<template>
  <rx-layout>
    <div slot="left" width="220" showButton="true" :showModuleLeft="false">
      <rx-fit>
        <rx-category-treeeditor
          cat-key="UREPORT2"
          :statisticConfig="statisticConfig"
          :edit="true"
          @handSelect="handSelect"
          :async="true"
          v-if="isShowManageTree"
          :isAdmin="isManageToTree"
          :checkToDel="true"
        ></rx-category-treeeditor>
      </rx-fit>
    </div>
    <div slot="center" style>
      <rx-fit :isheader="isheader">
        <div slot="toolheader" foldheader="true" foldbtn="false" border="false">
          <div class="table-operator">
            <rx-button alias="ureportFileAdd" :butn-icon="'plus'" :butn-type="'primary'" :show-no-right="true" @click="addUreport">{{$ti18('rxList.newBtn','新建')}}</rx-button>
              <a-button v-if="selectedRowKeys.length > 0"
                        type="primary"
                        icon="switcher" @click="openCategoryDialog">
                  {{$ti18('rxList.changeCategory','切换分类')}}
              </a-button>
            <a-dropdown>
              <a-button> {{$ti18('rxList.moreBtn','更多')}} <a-icon type="down" /> </a-button>
              <a-menu slot="overlay">
                <a-menu-item key="1" @click="doImport"> <i class="iconfont icondaoru"></i>{{$ti18('rxList.importBtn','导入')}} </a-menu-item>
                <a-sub-menu >
                  <span slot = "title"><i class="iconfont icondaochu"></i>{{$ti18('rxList.exportBtn','导出')}}</span>
                    <a-menu-item @click="doExport('1')"><i class="iconfont icondaochu"></i>{{$ti18('rxList.exportSelected','导出选中')}}
                    </a-menu-item>
                    <a-menu-item @click="doExport('2')"><i class="iconfont icondaochu"></i>{{$ti18('rxList.exportResults','导出查询结果')}}
                    </a-menu-item>
                </a-sub-menu>
                <a-menu-item
                  key="2"
                  @click="edit()"
                  v-if="editEnable && selectedRowKeys.length > 0"
                  alias="formRuleEdit"
                  :butn-type="'primary'"
                  :show-no-right="false"
                >
                  <a-icon type="edit" />{{$ti18('rxList.editBtn','编辑')}}
                </a-menu-item>
                <a-menu-item
                  key="3"
                  @click="delByIds(selectedRowKeys)"
                  v-if="removeEnable && selectedRowKeys.length > 0"
                  alias="formRuleDelete"
                  :butn-type="'danger'"
                  :show-no-right="false"
                >
                  <a-icon type="delete" />{{$ti18('rxList.delBtn','删除')}}
                </a-menu-item>
                <a-menu-item
                      key="4"
                      @click="changeExport(exportConf)"
                      v-if="selectedRowKeys.length > 0"
                      alias="formRuleDelete"
                      :butn-type="'primary'"
                      :show-no-right="false"
                  >
                      <a-icon type="switcher"/>
                      {{$ti18('rxList.changeExport','切换导出')}}
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </div>
          <span class="search-btn-box" v-if="!isheader">
            <span class="search-btn" @click.stop="searchshow"><i class="iconfont iconguolv"></i>{{$ti18('rxList.leachBtn','过滤')}}</span>
          </span>
        </div>
        <div btnalign="right" slot="searchbar" v-if="fitSearch" @search="search" @cancel="cancel"
             @close="closeSearchbar">
          <a-form :layout="colLayout">
            <a-row :gutter="24">
              <a-col :span="colSpan">
                <a-form-item :label="i18n('form.reportName','报表名称')">
                  <a-input :placeholder="i18n('form.reportName','报表名称','input')" v-model="queryParam.Q_NAME__S_LK"/>
                </a-form-item>
              </a-col>
              <a-col :span="colSpan" v-if="!curApp.appId">
                 <a-form-item :label="$ti18('rxForm.appId', '应用')">
                        <rx-search-app @change="appChange" v-model="searchApps">
                        </rx-search-app>
                 </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <rx-grid
                ref="table"
                :allowRowSelect="true"
                :multiSelect="true"
                :columns="columns"
                :defaultPageSize="10"
                :bordered="isBorder"
                url="/api-ureport/ureport2/core/ureportFile/query"
                :queryParam="queryParam"
                data-field="result.data"
                :pageSizeOptions="['10','30','40']"
                id-field="id"
                :loadDataOnstart="true"
                @selectChange="onSelectChange"
        >
            <span slot="exportApp">
                         {{ exportI18n('export.isExport','导出') }}
                        <export-app/>
                    </span>
            <span slot="appId" slot-scope="{ text, record }">
                {{allApps[text]?$i18(allApps[text].appName,'应用名称'):$ti18('rxList.noAppName','无')}}
            </span>
          <span slot="isExport" slot-scope="{ text, record }">
                <a-tag :color="text == 1 ? 'green' : 'red'">
                    <span>{{ text == 1 ? exportI18n('export.yes','是') : exportI18n('export.no','否') }}</span>
                </a-tag>
          </span>
          <span slot="action" slot-scope="{ text, record }" class="actionIcons">
            <span v-if="editEnable " @click="editUreport(record.name,'designer')">{{$ti18('rxList.editBtn','编辑')}}</span>
            <span  @click="editUreport(record.name,'preview')">{{i18n('list.viewPrint','预览打印')}}</span>
            <span  @click="deployMenu(record)">{{$ti18('rxList.deployMenu','发布菜单')}}</span>
            <span v-if="removeEnable " @click="delByIds([record.id])">{{$ti18('rxList.delBtn','删除')}}</span>
            <span @click="setExport(record,exportConf)">{{record.isExport == 1 ? exportI18n('export.noExport','不导出') : exportI18n('export.exported','导出')}}</span>
          </span>
        </rx-grid>
      </rx-fit>
    </div>
  </rx-layout>
</template>

<script>
  import RxCategoryTreeeditor from "@/components/redxun/rx-category-treeeditor";
  import UreportFileApi from '@/api/form/core/ureportFile'
  import {BaseList,Util,TokenUtil} from "@lowcode/jpaas-common-lib";
  import FormImport from './FormImport';
  import DialogBox from "@/assets/js/DialogBox";
  import { mapState} from 'vuex';
  import exportApp from "@/views/modules/share/exportApp";
  import AppSearch from "@/views/modules/share/AppSearch";
  import RxSearchApp from "@/views/modules/share/rx-search-app";
  import switchExport from "@/utils/switchExport";
  import ChangeCategory from "@/views/modules/share/ChangeCategory.js"

  export default {
    name: 'UreportFileList',
    mixins: [BaseList,AppSearch,switchExport,ChangeCategory],
    components: {
        RxCategoryTreeeditor,
        exportApp,
        RxSearchApp
    },
      computed: {
          ...mapState({
              // 所属应用
              allApps: state => state.appSetting ? state.appSetting.allApps : {}
          }),
      },
    data() {
      return {
        columns: [
          {
            title: this.$ti18('rxList.index', '序号'),
            type: 'indexColumn',
            width: 40,
            dataIndex: 'serial',
            scopedSlots: {customRender: 'serial'}
          },

          {
              title: this.i18n('form.reportName','报表名称'),
              dataIndex: 'name',
              width: 150
          },
            {
                title: this.i18n('form.app','所属应用'),
                dataIndex: 'appId',
                width: 140,
                sortField: 'APP_ID_',
                scopedSlots: {customRender: 'appId'}
            },

            {
                dataIndex: 'isExport',
                slots: { title: 'exportApp' },
                width: 60,
                scopedSlots: {customRender: 'isExport'}
            },
            { title: this.$ti18('rxForm.createTime','创建时间'), dataIndex: 'createTime', sorter:true,sortField:'CREATE_TIME_', width: 140},
            {title: this.$ti18('rxList.action','操作'), width: 100, dataIndex: 'action', scopedSlots: {customRender: 'action'}}
        ],
        comment: this.i18n('list.ureport','ureport报表'),
        treeId:"",
        accessToken:"",
        QueryData:{},
        widthHeight:['800px','600px'],
        statisticConfig: {
              type:"static_ureport",
              table:"UREPORT_FILE t",
              field:"CATEGORY_ID_",
              whereConf:[]
         },
          /**
           * 导出配置
           */
          exportConf:{
              Api:UreportFileApi,
              id:"id"
          },
          //变更分类配置
          categoryConfig:{
              Api:UreportFileApi,
              catKey:"UREPORT2",
              gridRef:"table"
          }
      }
    },
    created(){
        this.isUserManager(this.$route.query.appId);
        this.getAccessToken();
        this.needFilterAppId("isAppMenu");
        this.columns=this.removeAppColumn(this.curApp.appId,this.columns)
    },
    methods:{
        i18n(name, text, key) {
                return this.$ti18(name, text, "ureportFile", key);
        },
        exportI18n(name,text,key){
            return this.$ti18(name,text,"appExport",key);
        },
        edit(){
            if(this.selectedRows.length==0){
                this.$message.warn("没有选择记录!");
                return;
            }
            if(this.selectedRows.length>1){
                this.$message.warn("请选择一行记录修改");
                return;
            }


            let name=this.selectedRows[0].name;
            let appId=this.curApp.appId;
            var url="/ureport/designer?_u=qiaolin-"+name+"&accessToken="+ this.accessToken+"&appId="+appId;;;
            window.open(url)
        },
      editUreport(name,type){
          let appId=this.curApp.appId;
          var url="/ureport/"+type+"?_u=qiaolin-"+name+"&accessToken="+ this.accessToken+"&appId="+appId;;
          window.open(url)
      },
      addUreport(){
        if(!this.treeId || this.treeId=='0'){
          this.$warning({
            title: this.i18n('cateEmpty','报表分类为空'),
            content: this.i18n('selectLeft','请先选中左边报表分类'),
          });
          return;
        }
        let appId=this.curApp.appId;
        var url="/ureport/designer?categoryId="+this.treeId+"&accessToken="+ this.accessToken+"&appId="+appId;
        window.open(url)
      },
      getAccessToken(){
        this.accessToken=TokenUtil.getToken();
      },
      handSelect(curRow){
        this.curTree = curRow
        this.treeId=curRow.treeId;
        if(this.treeId!="0"){
            this.queryParam.Q_CATEGORY_ID__S_EQ=this.treeId;
        }else {
            delete this.queryParam.Q_CATEGORY_ID__S_EQ;
        }
        this.loadData(this.queryParam);
      },
      delById(ids){
        return UreportFileApi.del({ ids: ids.join(',') });
      },
      getListByParams(parameter){
        return UreportFileApi.query(parameter)
      },
       search(){
        this.$refs.table.loadData();
      },
      cancel(){
          this.resetSearch();
      },
      closeSearchbar(){
        //关闭过滤弹窗；（点击X触发）
        this.fitSearch = false ;
      },

      doExport(isSelected) {
            var exportList = [];
            //选中的导出
            if (isSelected == "1") {
                exportList = this.$refs.table.getSelectedRows();
                if (!exportList || exportList.length == 0) {
                    this.$warning({
                        title: this.$ti18('rxMsa.masWarn.delInfo','警告'),
                        content: this.i18n('exportTips','请选择需要导出的记录！'),
                    });
                    return;
                }
                let solutionIds = []
                exportList.forEach((item) => {
                    solutionIds.push(item.id)
                })
                this.QueryData.params = {
                    ids: solutionIds.toString()
                }
            } else {
                // 导出所查询的
                this.QueryData.params = {
                    isQuery: 0,
                }
                this.QueryData.params = Object.assign(this.QueryData.params, this.queryParam)
            }
            if (this.$refs.table.dataAction == "") {
                this.$warning({
                    title: this.$ti18('rxMsa.masWarn.delInfo','警告'),
                    content: this.i18n('exportError','该分类没有数据！'),
                });
                return;
            }
          UreportFileApi.listExport(this.QueryData)
        },
      doImport() {
        if (!this.curTree || !this.curTree.treeId) {
          this.$warning({
            title: this.$ti18('rxMsa.masWarn.delInfo','警告'),
            content: this.i18n('selectCate','请选择报表的分类！'),
          });
          return
        }
        var treeId = this.curTree.treeId
        Util.open(
          {
            component: FormImport,
            curVm: this,
            widthHeight: ['800px', '600px'],
            title: this.i18n('list.reportImport','报表导入'),
            data: {
              treeId: treeId,
              callback: function (params) {
                let self = this;
                UreportFileApi.doImport(params).then(res => {
                  this.isSpinning = false;
                  if (!res.success) {
                    self.$confirm({
                      title: this.$ti18('rxMsa.masWarn.delInfo','警告'),
                      content: this.i18n('importError','导入失败！'),
                        okText:this.$ti18('rxForm.ackBtn','确认'),
                        cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                    });
                    return;
                  }
                  self.getUpdataSqls(res.data);
                });
              }
            }
          },function (action) {
          });
      },
      deployMenu(record) {
        var url = "/ureport/preview?_u=qiaolin-"+record.name+"&accessToken"
        let name=record.name.replace('.ureport.xml',"");
        DialogBox.openDeploymenuDialog(
          {
            releaseId: record.id,
            name: name,
            key: name + '_Ureport',
            params: url,
            settingType: "iframe",
            curAppObj:this.curApp,
          },
          {
            curVm: this,
            widthHeight: ['600px', '600px'],
          }
        )
      },
    }
  }
</script>
<style scoped>

</style>

